import React, { useEffect, useRef, useState, useMemo, useContext } from 'react';
import { SchemaManage } from '@/components/SchemaComponent';
import { connect } from 'umi';
import { WasteMaterialsAPI } from '../common/type';
import { getTableColumns } from '../mconfig';
import { assetListManageServices, cancelService } from '../services';
import { DeleteOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { OneModal } from '@/components/one-ui';
import { message } from 'antd';
import { useDataSourceTable } from '../../AssetList/mconfig/useDataSourceTable';

const WasteMaterialsControllerView: React.FC<WasteMaterialsAPI.IMaterialManageView> = ({ curRes }) => {
  /** 管理页services */
  const {
    getAssetListTableData,
    data,
    loading,
    pagination,
    searchList,
    // manageTableParams,
    otherParams,
    loadMdicMapList,
  } = assetListManageServices(curRes);

  const [isShowCancel, setIsShowCancel] = useState<any>({
    isShow: false,
    records: [],
    isAll: false,
  });

  /** 管理页的ref */
  const MaterialManageViewRef: any = useRef();

  /** 保存展示的表格数据 */
  const [dataSourceTable, setDataSourceTable] = useState<Record<string, any>[]>([]);

  /** 保存选中数据 */
  const [selectRowKeys, setSelectRowKeys] = useState<Record<string, any>>({ rowKeysList: [], valList: [] });

  /** 保存表格展开行的key值 */
  const [tableExpantKeys, setTableExpantKeys] = useState<string[]>([]);

  /** 处理是否有子资产 */
  const { onExpandTable, childLoading } = useDataSourceTable(data?.rows, dataSourceTable, setDataSourceTable, tableExpantKeys, setTableExpantKeys);

  /** 切换头部方法 */
  const onSwitch = (key: string | undefined | number, searchValues: any, params: any) => {
    getAssetListTableData({ ...params, ...searchValues });
  };

  /** 重置方法 */
  const onReset = (otherParams: WasteMaterialsAPI.IAssetTableRequestType) => {
    getAssetListTableData({ ...otherParams });
  };

  /** 搜索方法 */
  const onSearch = (otherParams: WasteMaterialsAPI.IAssetTableRequestType) => {
    getAssetListTableData({ ...otherParams });
  };

  /** 表格刷新数据 */
  const reloadTableData = () => {
    getAssetListTableData({});
    setSelectRowKeys({ rowKeysList: [], valList: [] });
  };

  /** 分页方法 */
  const onPageChange = (current: any, pageSize: any, params: any) => {
    getAssetListTableData({ pageSize, current, ...params });
  };

  const cancelCallback = (res) => {
    if (res && res.msgFlag) {
      message.success(res.msg || '操作成功');
    } else {
      message.error(res.msg || '操作失败');
    }
    reloadTableData();
  };

  const { cancelRun, cancelLoading } = cancelService(cancelCallback);

  /** 设置多选框 */
  const oversightMemo = useMemo(() => {
    let rowSelectInfo: Record<string, any> = {};
    rowSelectInfo = {
      rowSelection: {
        type: 'checkBox',
        getCheckboxProps: (record: Record<string, any>) => ({
          disabled: record.resultantAsset || record.pId,
        }),
        selectedRowKeys: selectRowKeys?.rowKeysList,
        onChange: (selectedRowKeys: React.Key[], selectedValList) => {
          setSelectRowKeys({
            rowKeysList: selectedRowKeys,
            valList: selectedValList,
          });
        },
      },
    };
    return rowSelectInfo;
  }, [selectRowKeys]);

  /**Table操作列的事件池*/
  const getTableOperateFuncs: any = {
    /**报废按钮*/
    onCancel(record) {
      let ids: Record<string, any>[] = [];
      ids.push(record?.id);
      // 弹窗提示  是否报废
      setIsShowCancel({
        isShow: true,
        records: ids,
        isAll: false,
      });
    },
  };

  // 报废物资
  const handleCancel = () => {
    cancelRun({ ids: isShowCancel.records });
    // 关闭弹窗
    setIsShowCancel({
      isShow: false,
      records: [],
      isAll: false,
    });
  };

  /** Table的columns集合 */
  const columns: Record<string, any>[] = useMemo(() => {
    return getTableColumns(curRes, getTableOperateFuncs);
  }, [curRes]);

  /** 管理页面头部操作集合 */
  const tableActionList: WasteMaterialsAPI.IHeaderActionType = useMemo(() => {
    return [
      {
        title: '报废',
        visible: curRes?.['/assetStuff/editAssetStuff'],
        type: 'primary',
        icon: <DeleteOutlined />,
        onClick: () => {
          if (selectRowKeys?.valList?.length > 0) {
            const idArray = selectRowKeys?.valList?.map((item) => item.id);
            setIsShowCancel({
              isShow: true,
              records: idArray,
              isAll: true,
            });
          } else {
            message.warning('请至少选择一个物资！');
          }
        },
      },
    ];
  }, [curRes, selectRowKeys, dataSourceTable, otherParams]);

  useEffect(() => {
    if (history.location.pathname == '/materialAndAssetController/manage') {
      reloadTableData();
    }
  }, [history.location.pathname]);

  return (
    <>
      <div
        id={'custom-preview-container'}
        style={{
          position: 'relative',
          overflow: 'hidden',
          height: '100%',
          width: '100%',
        }}
      >
        <SchemaManage
          ref={MaterialManageViewRef}
          searchProps={{
            switchList: [], //头部切换列表
            searchList,
            onSwitch,
            onReset,
            onSearch,
          }}
          actionList={tableActionList} // 操作按钮
          tableProps={{
            columns: columns,
            dataSource: dataSourceTable ? dataSourceTable : [],
            rowKey: 'id',
            loading: loading || cancelLoading || childLoading,
            pagination: pagination as any,
            onPageChange: onPageChange,
            expandable: {
              // expandIcon: manageTableExpandIcon,
              onExpand: onExpandTable,
              expandedRowKeys: tableExpantKeys,
            },
            ...oversightMemo,
          }}
        />

        {/* 报废弹窗 */}
        {isShowCancel.isShow && (
          <OneModal
            title="提示"
            open={isShowCancel.isShow}
            onOk={handleCancel}
            onCancel={() => {
              setIsShowCancel({ isShow: false, records: [], isAll: false });
            }}
            children={`物资确认报废?`}
          />
        )}
      </div>
    </>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(WasteMaterialsControllerView);
